package com.demo.helloworld.logic;

import com.demo.helloworld.bo.User;
import com.demo.helloworld.dao.UserDAO;
import com.outstanding.framework.base.OutstandingLogic;
import com.outstanding.framework.base.transaction.OutstandingTransactionCallback;
import com.outstanding.framework.base.transaction.OutstandingTransactionTemplate;
import com.outstanding.framework.core.PendingException;
import com.outstanding.framework.core.ReturnCode;
import com.outstanding.framework.core.SysCode;
import com.outstanding.framework.utils.NumberUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.util.NumberUtils;

/**
 * 所有的逻辑层类都需要继承 OutstandingLogic 逻辑类含：业务的处理，事务的处理，逻辑内的业务流程串接 逻辑层代码
 * 必须加上spring的注解 @Service
 *
 */
@Service
public class SayHelloLogic extends OutstandingLogic {
	
	
	
	/**
	 * 新事务的模版
	 */
	@Autowired
	private OutstandingTransactionTemplate newTransactionTemplate;

	public OutstandingTransactionTemplate getNewTransactionTemplate() {
		return newTransactionTemplate;
	}

	
	@Autowired
	private UserDAO dao;

	public void say() {
		info("hello world");
		User user = new User();
		user.setName("sayHelloLogic");
		dao.addUser(user);
	}
	
	
	
	
	
 /**
	 * 以下两个方法是演示 单服务事务情况。
	 * 
	 * @param 
	 * @throws PendingException
	 */

	public ReturnCode commit(final User user) throws PendingException {

		return newTransactionTemplate.execute(new OutstandingTransactionCallback<ReturnCode>() {

			/**
			 * 此方法必须抛出PendingException异常
			 */
			@Override
			public ReturnCode doInTransaction(TransactionStatus status) throws PendingException {
				debug("调用commitSuccess");
				int count = dao.addUser(user);
				debug(String.valueOf(user.getId()));
				if (count == 1 && NumberUtil.compare(user.getAge(), 1) >=0) {
					return SysCode.SUCCESS;
				} else {
					status.setRollbackOnly();
					throw new PendingException(LogicRCode.T0001, "SQL执行异常");
				}

			}
		});
	}
}
